﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using SciLorsGroovesharkAPI.Groove.Functions;
using centrafuse.Plugins;
using System.Net;
using System.IO;
using System.Drawing;
using System.Threading;
using System.ComponentModel;

namespace Grooveshark
{
    public partial class Grooveshark
    {
        private CFControls.CFAdvancedList playlistView;

        private LinkedList<SearchArtist.SearchArtistResult> shuffledPlaylist = new LinkedList<SearchArtist.SearchArtistResult>();
        private DataTable playlistTable;
        private BindingSource playlistBindingSource;

        private void playlistUpButton_Click(object sender, MouseEventArgs e)
        {
            this.playlistView.PageUp();
        }

        private void playlistDownButton_Click(object sender, MouseEventArgs e)
        {
            this.playlistView.PageDown();
        }

        void playlistView_LinkedItemClick(object sender, CFControlsExtender.Listview.LinkedItemArgs e)
        {
            switch (e.LinkId)
            {
                case "Delete":
                    int itemId = e.ItemId;
                    if (e.ItemId < this.playlistTable.Rows.Count)
                    {
                        DataRow row = this.playlistTable.Rows[e.ItemId];
                        SearchArtist.SearchArtistResult song = row["Object"] as SearchArtist.SearchArtistResult;
                        
                        if (song == currentSong)
                        {
                            NextSong(true);
                        }

                        this.playlistTable.Rows.RemoveAt(e.ItemId);

                        shuffledPlaylist.Remove(song);

                        this.playlistView.Refresh();
                    }
                    break;
            }
        }

        private void favoritesButton_Click(object sender, MouseEventArgs e)
        {
            if (!login)
            {
                CF_displayMessage("You are not logged in");
            }
            else
            {
                ThreadPool.QueueUserWorkItem(delegate(object obj)
                {
                    ShowInfo("Retrieving favorites...");
                    List<SearchArtist.SearchArtistResult> allSongs = null;
                    lock (ClientLock)
                    {
                        try
                        {
                            allSongs = Client.FavoriteSongs(ClientUserID).result;
                        }
                        catch
                        {
                            ResetClient();
                            try
                            {
                                allSongs = Client.FavoriteSongs(ClientUserID).result;
                            }
                            catch (Exception ex)
                            {
                                ReportException(ex);
                                HideInfo();
                                return;
                            }
                        }
                    }

                    PopulateSearchResults(allSongs, false);
                    this.HideInfo();
                    this.BeginInvoke(new MethodInvoker(delegate()
                    {
                        ShowSearchResultScreen();
                    }));
                });
            }
        }

        private void myMusicButton_Click(object sender, MouseEventArgs e)
        {
            if (!login)
            {
                CF_displayMessage("You are not logged in");
            }
            else
            {
                ThreadPool.QueueUserWorkItem(delegate(object obj)
                {
                    ShowInfo("Retrieving your music...");
                    List<SearchArtist.SearchArtistResult> allSongs = new List<SearchArtist.SearchArtistResult>();
                    lock (ClientLock)
                    {
                        userGetSongsInLibrary.MyResult result = null;
                        int currentPage = 0;
                        do
                        {
                            try
                            {
                                result = Client.UserLibarySong(ClientUserID, currentPage).result;
                                allSongs.AddRange(result.Songs);
                                currentPage++;
                            }
                            catch (Exception ex)
                            {
                                //not gonna retry here, too complicated
                                ReportException(ex);
                                ResetClient();
                                HideInfo();
                                return;
                            }
                        }
                        while (result.hasMore);
                    }

                    PopulateSearchResults(allSongs, true);
                    HideInfo();
                    this.BeginInvoke(new MethodInvoker(delegate()
                    {
                        ShowSearchResultScreen();
                    }));
                });
            }

        }

        private void label_Click(object sender, MouseEventArgs e)
        {
            CFControls.CFLabel label = sender as CFControls.CFLabel;
            if (label != null)
            {
                CF_displayMessage(label.Text);
            }
        }

        void webClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null && (int)e.UserState == currentSong.SongID)
            {
                MemoryStream ms = new MemoryStream(e.Result);
                ms.Position = 0;

                Image img = null;
                try
                {
                    img = Image.FromStream(ms);
                }
                catch
                {

                }
                finally
                {
                    ms.Dispose();
                }
                
                CF_setPictureImage("albumArtBox", null);
                if (currentSongImage != null)
                    currentSongImage.Dispose();
                currentSongImage = img;
                CF_setPictureImage("albumArtBox", img);
            }
        }

        private void SetupPlaylistScreen()
        {
            playlistView = this.advancedlistArray[CF_getAdvancedListID("playList")];
            playlistView.LinkedItemClick += new EventHandler<CFControlsExtender.Listview.LinkedItemArgs>(playlistView_LinkedItemClick);
            playlistView.DoubleClick += new EventHandler<CFControlsExtender.Listview.ItemArgs>(playlistView_DoubleClick);
            playlistView.DataBinding = playlistBindingSource;
            playlistView.Refresh();

            this.CF_createButtonClick("playlistUpButton", new MouseEventHandler(playlistUpButton_Click));
            this.CF_createButtonClick("playlistDownButton", new MouseEventHandler(playlistDownButton_Click));
            this.CF_createButtonClick("searchButton", new MouseEventHandler(searchButton_Click));
            this.CF_createButtonClick("myMusicButton", new MouseEventHandler(myMusicButton_Click));
            this.CF_createButtonClick("favoritesButton", new MouseEventHandler(favoritesButton_Click));
            //this.CF_createButtonClick("playListsButton", new MouseEventHandler(playListsButton_Click));
            this.CF_createButtonClick("shuffleButton", new MouseEventHandler(shuffleButton_Click));
            this.CF_createButtonClick("clearPlaylistButton", new MouseEventHandler(clearPlaylistButton_Click));
            

            this.CF_createLabelClick("songLabel", new MouseEventHandler(label_Click));
            this.CF_createLabelClick("artistLabel", new MouseEventHandler(label_Click));
            this.CF_createLabelClick("albumLabel", new MouseEventHandler(label_Click));

            CF_setPictureImage("albumArtBox", currentSongImage);

            CF_updateText("songLabel", currentSong != null ? currentSong.SongName : string.Empty);
            CF_updateText("artistLabel", currentSong != null ? currentSong.ArtistName : string.Empty);
            CF_updateText("albumLabel", currentSong != null ? currentSong.AlbumName : string.Empty);

            CF_setPictureImage("shufflePictureBox", ShuffleState ? Resources.suffle : Resources.straight);

            ScrollToCurrentSong();
        }

        private void ScrollToCurrentSong()
        {
            if (currentSong != null)
            {
                foreach (DataRow row in playlistTable.Rows)
                {
                    SearchArtist.SearchArtistResult song = row["Object"] as SearchArtist.SearchArtistResult;

                    if (song != null && song == currentSong)
                    {
                        int index = playlistTable.Rows.IndexOf(row);
                        this.BeginInvoke(new MethodInvoker(delegate()
                            {
                                this.playlistBindingSource.Position = index;
                                playlistView.SelectedIndex = index;
                            }));
                        break;
                    }
                }
            }
        }

        void clearPlaylistButton_Click(object sender, MouseEventArgs e)
        {
            CFDialogParams dialogParams = new CFDialogParams("Are you sure you want to clear the whole playlist?");
            DialogResult result = CF_displayDialog(CF_Dialogs.YesNo, dialogParams);
            if (result == System.Windows.Forms.DialogResult.Yes || result == System.Windows.Forms.DialogResult.OK)
            {
                Stop();
                playlistTable.Clear();
                shuffledPlaylist.Clear();
                playlistView.Refresh();
            }
        }
        
        void shuffleButton_Click(object sender, MouseEventArgs e)
        {
            ShuffleState = !ShuffleState;
            CF_setPictureImage("shufflePictureBox", ShuffleState ? Resources.suffle : Resources.straight);
        }

        void playlistView_DoubleClick(object sender, CFControlsExtender.Listview.ItemArgs e)
        {
            if (playlistTable.Rows.Count > e.ItemId)
            {
                CF_systemCommand(CF_Actions.BEEPSOUND);
                DataRow songRow = playlistTable.Rows[e.ItemId];
                SearchArtist.SearchArtistResult song = songRow["Object"] as SearchArtist.SearchArtistResult;
                PlaySong(song);
            }
        }

        private void Search(bool group)
        {
            CFDialogParams searchDialogParams = new CFDialogParams("Search by artist and/or song name.");
            CFDialogResults results = new CFDialogResults();
            DialogResult result = CF_displayDialog(CF_Dialogs.OSK, searchDialogParams, results);
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                string searchText = results.resultvalue;
                ThreadPool.QueueUserWorkItem(delegate(object param)
                {
                    ShowInfo("Searching...");
                    lock (ClientLock)
                    {
                        List<SearchArtist.SearchArtistResult> searchResults = null;
                        try
                        {
                            searchResults = Client.SearchArtist(searchText).result.result;
                        }
                        catch
                        {
                            ResetClient();
                            try
                            {
                                searchResults = Client.SearchArtist(searchText).result.result;
                            }
                            catch (Exception ex)
                            {
                                ReportException(ex);
                                HideInfo();
                                return;
                            }
                        }
                        
                        PopulateSearchResults(searchResults, group);
                        HideInfo();
                        this.BeginInvoke(new MethodInvoker(delegate()
                        {
                            ShowSearchResultScreen();
                        }));
                    }
                });
            }
        }


        private void searchButton_Click(object sender, MouseEventArgs e)
        {
            Search(false);
        }

        private void MyFavorites_LongPressed()
        {
            ThreadPool.QueueUserWorkItem(delegate(object obj)
            {
                ShowInfo("Retrieving popular songs...");
                List<SearchArtist.SearchArtistResult> popularSongs = null;
                lock (ClientLock)
                {
                    try
                    {
                        popularSongs = Client.PopularSongs().result.Songs;
                    }
                    catch
                    {
                        ResetClient();
                        try
                        {
                            popularSongs = Client.PopularSongs().result.Songs;
                        }
                        catch (Exception ex)
                        {
                            ReportException(ex);
                            HideInfo();
                            return;
                        }
                    }
                }

                PopulateSearchResults(popularSongs, false);
                HideInfo();
                this.BeginInvoke(new MethodInvoker(delegate()
                {
                    ShowSearchResultScreen();
                }));
            });
        }
    }
}
